// $Id: listener.c 100 2011-10-21 15:05:36Z cedric.shih@gmail.com $
/*
 * Copyright 2011 Cedric Shih (cedric dot shih at gmail dot com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include "log.h"

#include "listener.h"

int niohttp_listener_list_add(struct niohttp_listener_list *list,
		niohttp_data_cb cb, void *cbarg)
{
	int rc;
	struct niohttp_listener *listener;

	if (!list || !cb) {
		rc = EINVAL;
		niohttp_error("null pointer(s)");
		goto finally;
	}

	niohttp_debug("adding to %p: cb=%p, arg=%p", list, cb, cbarg);

	if (!(listener = calloc(1, sizeof(struct niohttp_listener)))) {
		rc = errno ? errno : -1;
		niohttp_error("calloc: %s", strerror(rc));
		goto finally;
	}

	listener->cb = cb;
	listener->cbarg = cbarg;
	TAILQ_INSERT_TAIL(list, listener, entry);
	rc = 0;

finally:
	return rc;
}

void niohttp_listener_list_del(struct niohttp_listener_list *list,
		struct niohttp_listener *listener)
{
	niohttp_debug("removing from %p: %p", list, listener);

	TAILQ_REMOVE(list, listener, entry);
	free(listener);
}

void niohttp_listener_list_clear(struct niohttp_listener_list *list)
{
	struct niohttp_listener *listener;

	niohttp_debug("clearing");

	while ((listener = TAILQ_FIRST(list))) {
		niohttp_listener_list_del(list, listener);
	}
}
